#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <NTPClient.h>

//配置引脚
#define CONFIG_PIN    D7

char ssid_str[128]; //WIFI名称
char pass_str[128]; //WIFI密码

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "ntp1.aliyun.com",60*60*8, 30*60*1000);


//SmartConfig方式获取WIFI名称密码
void smartConfig()
{
  //设置WIFI模块为STA模式
  WiFi.mode(WIFI_STA);
  
  //smartconfig进行初始化
  WiFi.beginSmartConfig();

  //等待连接成功
  while (1) 
  {
    Serial.print(">");
    delay(1000);
    //如果连接成功后就打印出连接的WIFI信息
    if (WiFi.smartConfigDone())
    {
      sprintf(ssid_str, "%s", WiFi.SSID().c_str());
      sprintf(pass_str, "%s", WiFi.psk().c_str());
      break;
    }
  }
}

void setup() 
{
  //串口初数化
  Serial.begin(115200);
  delay(1000);
  Serial.println("\r\nSystem Init!\r\n");      
  delay(10);

  //配置按键初始化
  pinMode(CONFIG_PIN, INPUT);
  
  //存储数据初始化
  saveInit();
  
  //LED显示初始化
  ledShowInit();  
  delay(10);

  //获取WIFI名称和密码
  if(saveIsFristTimeRun() == true)
  {
    Serial.printf("\r\nSmartConfig...\r\n");
    //从SmartConfig获取
    smartConfig();
    delay(10);
  }
  else
  {
    Serial.printf("\r\nEeprom...\r\n");
    //从EEPROM获取
    saveGetSsid(ssid_str);
    saveGetPass(pass_str);
  }
  Serial.printf("\r\nSSID:%s\r\n", ssid_str);
  Serial.printf("\r\nPASS:%s\r\n", pass_str);
      
  //WIFI连接
  ledShowAllRed();
  WiFi.begin(ssid_str, pass_str);
  while ( WiFi.status() != WL_CONNECTED )
  {
    delay(1000);
    Serial.print (".");
  }
  ledShowAllGreen();
  delay(1000);

  //保存WIFI名称密码
  saveSetSsid(ssid_str);
  saveSetPass(pass_str);
  saveClearFristTimeRunFlag();
  
  //NTP服务初始化
  timeClient.begin();
  delay(10);
}

void loop() 
{
  //NTP获取时间
  timeClient.update();
  int hours = timeClient.getHours();
  int minutes = timeClient.getMinutes();
  int seconds = timeClient.getSeconds();
  Serial.printf("\r\nTime-%02d:%02d:%02d\r\n", hours, minutes, seconds);
  
  //LED刷新时间
  ledShowRefresh(hours, minutes, seconds);
  
  //按键判断长按5S则重新配置WIFI参数
  static int config_press_time = 0;
  int config_press = digitalRead(CONFIG_PIN);
  if(config_press == HIGH)
  {
    config_press_time++;
    Serial.printf("\r\nConfig_Pin_Low %d\r\n", config_press_time);

    if(config_press_time >= 5)
    {
      Serial.printf("\r\nSystem Reset!\r\n");
      saveSetFristTimeRunFlag();  //重新设置WIFI参数
      ESP.restart();
    }
  }
  else
  {
    config_press_time = 0;
  }

  delay(1000);
}
